package com.hr.service;

import com.hr.dao.UserDAO;
import com.hr.model.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserService implements UserDetailsService
{
    @Autowired
    UserDAO userDAO;

    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException
    {
        User user = userDAO.getUserByAccount(account);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在!");
        }
        return user;
    }

    public User getUserByUId(int uid)
    {
        return userDAO.getUserByUId(uid);
    }

    public void updatePW(int uid, String oldpass, String pass) throws Exception
    {
        User user = userDAO.getUserByUId(uid);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (encoder.matches(oldpass, user.getPassword())) {
            String encodePass = encoder.encode(pass);
            userDAO.updatePW(uid, encodePass);
            return;
        }
        throw new Exception("旧密码错误");
    }

    public void registry(String account, String password,String identity) throws Exception
    {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if(userDAO.getUserByAccount(account)!=null)
            throw new Exception("该账号已存在");

        password=encoder.encode(password);

        userDAO.insertUser(account,password,identity);
    }
}
